<template>
  <div class="record-maintenance pph-page-container">
    <el-card class="page-header pph-page-header">
      <h2>
        <el-icon><Setting /></el-icon>
        记录维护
      </h2>
      <p>按条件查询、编辑或删除历史记录。仅允许修改非敏感、非派生字段；删除用于整条误录重录。</p>
    </el-card>

    <el-card class="filters">
      <div class="search-container">
        <el-form :inline="true" @submit.prevent class="search-form">
          <!-- 第一行查询条件 -->
          <div class="form-row">
            <el-form-item label="日期范围">
              <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="生产线">
              <el-select v-model="filters.line_name" placeholder="选择生产线" style="width: 180px" clearable filterable>
                <el-option
                  v-for="line in lines"
                  :key="line.line_name"
                  :label="line.line_name"
                  :value="line.line_name"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="订单号">
              <el-input v-model="filters.order_number" v-trim-input placeholder="可留空" style="width: 200px" />
            </el-form-item>
            <el-form-item label="物料编码">
              <el-input v-model="filters.material_code" v-trim-input placeholder="可留空" style="width: 200px" />
            </el-form-item>
          </div>

          <!-- 第二行查询条件和操作按钮 -->
          <div class="form-row form-row-with-buttons">
            <div class="form-fields">
              <el-form-item label="产品型号">
                <el-input v-model="filters.product_name" v-trim-input placeholder="可留空" style="width: 200px" />
              </el-form-item>
              <el-form-item label="异常类别">
                <el-select v-model="filters.abnormality_category" placeholder="选择异常类别" style="width: 200px" clearable>
                  <el-option
                    v-for="category in abnormalityCategories"
                    :key="category.id"
                    :label="category.category_name"
                    :value="category.category_name"
                  />
                </el-select>
              </el-form-item>
            </div>

            <!-- 操作按钮区域 -->
            <div class="action-buttons">
              <el-button type="primary" @click="onSearch" :loading="loading" class="action-btn">
                <el-icon><Search /></el-icon>
                查询
              </el-button>
              <el-button @click="resetFilters" class="action-btn">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </div>
          </div>
        </el-form>
      </div>
    </el-card>

    <el-card>
      <el-table :data="rows" border height="60vh" v-loading="loading">
        <el-table-column prop="record_date" label="记录日期" width="110" />
        <el-table-column prop="line_name" label="生产线" width="110" />
        <el-table-column prop="order_number" label="订单号" width="160" />
        <el-table-column prop="material_code" label="物料编码" width="140" />
        <el-table-column prop="product_name" label="产品名称" width="180" show-overflow-tooltip />
        <el-table-column prop="demand_category" label="需求分类" width="120" />
        <el-table-column prop="customer_number" label="顾客号" width="120" />
        <el-table-column prop="start_time" label="开始时间" width="100" />
        <el-table-column prop="end_time" label="结束时间" width="100" />
        <el-table-column prop="quantity" label="完成数量" width="100" />
        <el-table-column prop="total_people" label="总人数" width="100" />
        <el-table-column prop="working_people" label="线上人员" width="100" />
        <el-table-column prop="offline_staff" label="线外人员" width="100" />
        <el-table-column prop="break_minutes" label="小休" width="80" />
        <el-table-column prop="abnormal_loss_minutes" label="异常" width="80" />
        <el-table-column prop="changeover_minutes" label="转产" width="80" />
        <el-table-column prop="maintenance_time" label="维护" width="80" />
        <el-table-column prop="belt_speed" label="皮带(秒/格)" width="110" />
        <el-table-column prop="abnormality_category" label="异常类别" width="120" />
        <el-table-column prop="abnormality_description" label="异常描述" width="150" show-overflow-tooltip />
        <el-table-column prop="abnormality_closed" label="异常已关闭" width="110">
          <template #default="{ row }">{{ (row.abnormality_closed === 1 || row.abnormality_closed === '1') ? '是' : '否' }}</template>
        </el-table-column>
        <el-table-column prop="is_standard_operating" label="符合标准" width="100">
          <template #default="{ row }">{{ (row.is_standard_operating === 1 || row.is_standard_operating === '1') ? '是' : '否' }}</template>
        </el-table-column>
        <el-table-column prop="is_main_product" label="主打产品" width="90">
          <template #default="{ row }">{{ (row.is_main_product === 1 || row.is_main_product === '1' || row.is_main_product === true) ? '是' : '否' }}</template>
        </el-table-column>
        <el-table-column prop="is_whole_machine" label="生产类型" width="120">
          <template #default="{ row }">{{ (row.is_whole_machine === 1 || row.is_whole_machine === '1') ? '整机生产' : '整机+电机生产' }}</template>
        </el-table-column>
        <el-table-column prop="calculated_pph" label="实际PPH" width="100" />
        <el-table-column prop="average_pph" label="PPH平均值" width="100" />
        <el-table-column prop="target_pph" label="目标PPH" width="100" />
        <el-table-column prop="estimate_pph" label="预估PPH" width="100" />
        <el-table-column prop="efficiency_rate" label="达成率%" width="90">
          <template #default="{ row }">
            {{ formatEfficiencyRate(row.efficiency_rate) }}
          </template>
        </el-table-column>
        <el-table-column prop="target_takt_time" label="节拍" width="80" />
        <el-table-column prop="target_motor_takt_time" label="整机节拍" width="90" />
        <el-table-column prop="target_record_date" label="目标值日期" width="110" />
        <el-table-column fixed="right" label="操作" width="160">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="openEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="confirmDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pager">
        <el-pagination background layout="prev, pager, next, sizes, total" :page-size="pageSize" :page-sizes="[10,20,50]" :current-page="page" :total="total" @current-change="(p:number)=>{page=p;loadData()}" @size-change="(s:number)=>{page=1;pageSize=s;loadData()}" />
      </div>
    </el-card>

    <el-drawer v-model="editing.visible" title="编辑记录" size="500px">
      <el-form label-width="110px">
        <!-- 只读字段区域 -->
        <div style="background-color: #f5f7fa; padding: 12px; margin-bottom: 16px; border-radius: 4px;">
          <div style="color: #909399; font-size: 12px; margin-bottom: 8px;">基础信息（不可修改）</div>
          <el-form-item label="订单号"><el-input v-model="editing.data.order_number" readonly /></el-form-item>
          <el-form-item label="物料编码"><el-input v-model="editing.data.material_code" readonly /></el-form-item>
          <el-form-item label="产品名称"><el-input v-model="editing.data.product_name" readonly /></el-form-item>
          <el-form-item label="需求分类"><el-input v-model="editing.data.demand_category" readonly /></el-form-item>
          <el-form-item label="顾客号"><el-input v-model="editing.data.customer_number" readonly /></el-form-item>
          <el-form-item label="生产线"><el-input v-model="editing.data.line_name" readonly /></el-form-item>
        </div>

        <!-- 可编辑字段区域 -->
        <div style="color: #909399; font-size: 12px; margin-bottom: 8px;">可编辑字段</div>
        <el-form-item label="记录日期"><el-date-picker v-model="editing.data.record_date" type="date" value-format="YYYY-MM-DD" /></el-form-item>
        <el-form-item label="开始时间">
          <TimeInput v-model="editing.data.start_time" placeholder="如 926 → 09:26" defaultOnOpen="start" />
        </el-form-item>
        <el-form-item label="结束时间">
          <TimeInput v-model="editing.data.end_time" placeholder="如 1325 → 13:25" defaultOnOpen="end" />
        </el-form-item>
        <el-form-item label="完成数量"><el-input v-model.number="editing.data.quantity" type="number" /></el-form-item>
        <el-form-item label="线上人员"><el-input v-model.number="editing.data.working_people" type="number" /></el-form-item>
        <el-form-item label="线外人员"><el-input v-model.number="editing.data.offline_staff" type="number" /></el-form-item>
        <el-form-item label="小休分钟"><el-input v-model.number="editing.data.break_minutes" type="number" /></el-form-item>
        <el-form-item label="异常分钟"><el-input v-model.number="editing.data.abnormal_loss_minutes" type="number" /></el-form-item>
        <el-form-item label="转产分钟"><el-input v-model.number="editing.data.changeover_minutes" type="number" /></el-form-item>
        <el-form-item label="维护分钟"><el-input v-model.number="editing.data.maintenance_time" type="number" /></el-form-item>
        <el-form-item label="皮带(秒/格)"><el-input v-model.number="editing.data.belt_speed" type="number" step="0.1" /></el-form-item>
        <el-form-item label="异常类别">
          <el-select v-model="editing.data.abnormality_category" placeholder="选择异常类别" clearable filterable>
            <el-option
              v-for="category in abnormalityCategories"
              :key="category.id"
              :label="category.category_name"
              :value="category.category_name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="异常描述">
          <el-input v-model="editing.data.abnormality_description" type="textarea" :rows="2" placeholder="可留空" />
        </el-form-item>
        <el-form-item label="异常已关闭">
          <el-switch v-model="editing.data.abnormality_closed" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="符合标准">
          <el-switch v-model="editing.data.is_standard_operating" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="主打产品">
          <!-- 统一使用正向逻辑：is_main_product（true=主打，false=非主打） -->
          <el-radio-group v-model="editing.data.is_main_product" size="small">
            <el-radio-button :label="true">是</el-radio-button>
            <el-radio-button :label="false">否</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生产类型">
          <!-- 1=整机生产；0=整机+电机生产。按左->右顺序排布，避免语义混淆 -->
          <el-radio-group v-model="editing.data.is_whole_machine" size="small">
            <el-radio-button :label="1">整机生产</el-radio-button>
            <el-radio-button :label="0">整机+电机生产</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <!-- 计算字段显示区域 -->
        <div style="background-color: #f0f9ff; padding: 12px; margin-top: 16px; border-radius: 4px;">
          <div style="color: #909399; font-size: 12px; margin-bottom: 8px;">计算字段（实时计算）</div>
          <el-form-item label="总人数"><el-input :value="computedTotalPeople" readonly /></el-form-item>
          <el-form-item label="净工作时间"><el-input :value="computedNetWorkingMinutes + ' 分钟'" readonly /></el-form-item>
          <el-form-item label="实际PPH"><el-input :value="computedActualPPH" readonly /></el-form-item>
          <el-form-item label="实际节拍时间"><el-input :value="computedActualTaktSeconds + ' 秒/件'" readonly /></el-form-item>
          <el-form-item label="效率达成率"><el-input :value="computedEfficiencyRate + '%'" readonly /></el-form-item>
        </div>
        <!-- 参考字段（只读） -->
        <div style="background-color: #f5f7fa; padding: 12px; margin-top: 12px; border-radius: 4px;">
          <div style="color: #909399; font-size: 12px; margin-bottom: 8px;">参考字段（只读）</div>
          <el-form-item label="目标值日期"><el-input :value="editing.data.target_record_date || '-'" readonly /></el-form-item>
          <el-form-item label="PPH平均值"><el-input :value="(editing.data.average_pph ?? '-')" readonly /></el-form-item>
          <el-form-item label="目标PPH"><el-input :value="(editing.data.target_pph ?? '-')" readonly /></el-form-item>
          <el-form-item label="预估PPH"><el-input :value="(editing.data.estimate_pph ?? '-')" readonly /></el-form-item>
        </div>

      </el-form>
      <template #footer>
        <el-button @click="editing.visible=false">取消</el-button>
        <el-button type="primary" @click="saveEdit" :loading="editing.loading">保存</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">

import { Setting, Search, Refresh } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { ref, reactive, onMounted, computed, watch } from 'vue'

import TimeInput from '@/components/common/TimeInput.vue'
import { pphService } from '@/services/pphService'

interface Row { id:number; [k:string]: any }

const loading = ref(false)
const rows = ref<Row[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(20)
const dateRange = ref<[string,string] | null>(null)
const abnormalityCategories = ref<any[]>([])
const lines = ref<any[]>([])
const filters = reactive<{
  line_name?: string;
  order_number?: string;
  material_code?: string;
  product_name?: string;
  abnormality_category?: string;
}>({})

// 记录维护页面采用"空白状态"策略：

// 默认日期范围：最近7天
function fmtDate(d: Date) {
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${y}-${m}-${day}`
}
function getLast7DaysRange(): [string, string] {
  const end = new Date()
  const start = new Date()
  start.setDate(end.getDate() - 6)
  return [fmtDate(start), fmtDate(end)]
}

// - 不保存搜索条件
// - 不自动加载数据
// - 用户必须手动查询
// 这样设计是为了确保数据操作的安全性和性能考虑

// 重置查询条件
function resetFilters() {
  dateRange.value = null
  filters.line_name = ''
  filters.order_number = ''
  filters.material_code = ''
  filters.product_name = ''
  filters.abnormality_category = ''

  // 重置后清空表格数据，等待用户手动查询
  rows.value = []
  total.value = 0
  page.value = 1

  ElMessage.success('查询条件已重置，请输入条件后点击查询')
}

// 加载生产线列表
async function loadLines() {
  try {
    const response = await pphService.getLines()
    lines.value = response.lines || []
  } catch (error: any) {
    console.error('获取生产线列表失败:', error)
    ElMessage.error('获取生产线列表失败')
  }
}

// 加载异常类别列表
async function loadAbnormalityCategories() {
  try {
    const response = await pphService.getAbnormalityCategories()
    abnormalityCategories.value = response.categories || []
  } catch (error: any) {
    console.error('获取异常类别列表失败:', error)
    ElMessage.error('获取异常类别列表失败')
  }
}

async function loadData(){
  try{
    loading.value = true
    const params: any = {
      page: page.value,
      limit: pageSize.value
    }
    if (dateRange.value) {
      params.start_date = dateRange.value[0]
      params.end_date = dateRange.value[1]
    }
    if (filters.line_name) params.line_name = filters.line_name
    if (filters.order_number) params.order_number = filters.order_number
    if (filters.material_code) params.material_code = filters.material_code
    if (filters.product_name) params.product_name = filters.product_name
    if (filters.abnormality_category) params.abnormality_category = filters.abnormality_category

    const data = await pphService.getRecords(params)
    rows.value = data.data || []
    // 兼容后端返回的分页结构 { pagination: { total } }
    const pagTotal = Number(data?.pagination?.total ?? data?.total ?? 0)
    total.value = isNaN(pagTotal) ? 0 : pagTotal
  }catch(e:any){
    ElMessage.error(e?.message || '查询失败')
  }finally{
    loading.value = false
  }
}

function onSearch(){
  // 每次点“查询”，回到第1页，避免旧页码影响结果展示
  page.value = 1
  loadData()
}

const editing = reactive<{ visible:boolean; data:Row; loading:boolean }>({ visible:false, data:{} as Row, loading:false })

async function openEdit(row:Row){
  editing.visible = true
  // 统一类型：将 '1'/'0' 转为数字，确保单选默认值正确
  const clone = JSON.parse(JSON.stringify(row))
  clone.is_standard_operating = Number(clone.is_standard_operating)
  // 旧字段已移除，直接使用 is_main_product
  clone.is_whole_machine = Number(clone.is_whole_machine)
  clone.abnormality_closed = (clone.abnormality_closed === undefined || clone.abnormality_closed === null) ? 0 : Number(clone.abnormality_closed)

  // 🔧 统一字段：直接使用 is_main_product 字段（1=主打，0=非主打）
  // 数据库迁移后，前后端都使用 is_main_product 字段
  // 兼容数字1、字符串'1'和boolean true
  clone.is_main_product = (clone.is_main_product === 1 || clone.is_main_product === '1' || clone.is_main_product === true)

  editing.data = clone

  // 🔧 获取最新的目标值和预估值用于参考显示
  await fetchTargetAndEstimateForEdit()
}

// 获取编辑记录的目标值和预估值
async function fetchTargetAndEstimateForEdit() {
  if (!editing.data.material_code || !editing.data.line_name || !editing.data.record_date) {
    return
  }

  try {
    const params = {
      material_code: editing.data.material_code,
      line_name: editing.data.line_name,
      record_date: editing.data.record_date,
      whole_machine: editing.data.is_whole_machine ? 'true' : 'false'
    }

    const response = await pphService.getPPHTargets(params)
    if (response.success) {
      // 更新参考字段
      editing.data.target_pph = response.target_pph
      editing.data.target_record_date = response.target_record_date
      editing.data.estimate_pph = response.estimate_pph

      console.log('📊 获取编辑参考值:', {
        target_pph: response.target_pph,
        estimate_pph: response.estimate_pph,
        target_record_date: response.target_record_date
      })
    }
  } catch (error) {
    console.warn('获取编辑参考值失败:', error)
    // 不显示错误提示，因为这只是参考值
  }
}

async function saveEdit(){
  try{
    editing.loading = true
    const id = editing.data.id

    // 只发送可编辑字段，计算字段由后端自动重算
    // 处理“异常类别取消”的场景：如果异常类别被清空，则同时清空描述并将关闭状态置为 null
    const normalizedCategory = editing.data.abnormality_category || ''
    const payload: any = {
      record_date: editing.data.record_date,
      start_time: editing.data.start_time,
      end_time: editing.data.end_time,
      quantity: editing.data.quantity,
      working_people: editing.data.working_people,
      offline_staff: editing.data.offline_staff,
      break_minutes: editing.data.break_minutes,
      abnormal_loss_minutes: editing.data.abnormal_loss_minutes,
      changeover_minutes: editing.data.changeover_minutes,
      maintenance_time: editing.data.maintenance_time,
      belt_speed: editing.data.belt_speed,
      abnormality_category: normalizedCategory,
      abnormality_description: normalizedCategory ? (editing.data.abnormality_description || '') : '',
      abnormality_closed: normalizedCategory ? (editing.data.abnormality_closed ?? 0) : null,
      is_standard_operating: editing.data.is_standard_operating,
      // 统一字段：前端 is_main_product(Boolean) 直接对应数据库 is_main_product(1=主打,0=非主打)
      is_main_product: (editing.data.is_main_product === true ? 1 : 0),
      // 生产类型保持数值 1/0
      is_whole_machine: Number(editing.data.is_whole_machine ?? 1)
    }

    await pphService.updateRecord(id, payload)
    ElMessage.success('保存成功')
    editing.visible=false
    loadData()
  }catch(e:any){
    ElMessage.error(e?.message || '保存失败')
  }finally{
    editing.loading = false
  }
}

// 计算字段的实时计算
const computedTotalPeople = computed(() => {
  const workingPeople = Number(editing.data.working_people || 0)
  const offlineStaff = Number(editing.data.offline_staff || 0)
  return workingPeople + offlineStaff || editing.data.total_people || 0
})

const computedNetWorkingMinutes = computed(() => {
  const startTime = editing.data.start_time
  const endTime = editing.data.end_time
  if (!startTime || !endTime) return 0

  try {
    // 计算总工作时间（分钟）
    const [startHour, startMin] = startTime.split(':').map(Number)
    const [endHour, endMin] = endTime.split(':').map(Number)

    let totalMinutes = (endHour * 60 + endMin) - (startHour * 60 + startMin)
    if (totalMinutes < 0) totalMinutes += 24 * 60 // 跨天处理

    // 减去各种损失时间
    const breakMinutes = Number(editing.data.break_minutes || 0)
    const abnormalLossMinutes = Number(editing.data.abnormal_loss_minutes || 0)
    const changeoverMinutes = Number(editing.data.changeover_minutes || 0)
    const maintenanceTime = Number(editing.data.maintenance_time || 0)

    const netMinutes = totalMinutes - breakMinutes - abnormalLossMinutes - changeoverMinutes - maintenanceTime
    return Math.max(0, netMinutes)
  } catch {
    return 0
  }
})

const computedActualPPH = computed(() => {
  const quantity = Number(editing.data.quantity || 0)
  const netMinutes = computedNetWorkingMinutes.value
  const totalPeople = computedTotalPeople.value

  if (netMinutes > 0 && totalPeople > 0) {
    const netHours = netMinutes / 60
    return Math.round((quantity / (netHours * totalPeople)) * 100) / 100
  }
  return 0
})

const computedActualTaktSeconds = computed(() => {
  const actualPPH = computedActualPPH.value
  if (actualPPH > 0) {
    return Math.round((3600 / actualPPH) * 100) / 100
  }
  return 0
})

const computedEfficiencyRate = computed(() => {
  const actualPPH = computedActualPPH.value
  const targetPPH = Number(editing.data.target_pph || 0)

  if (actualPPH > 0 && targetPPH > 0) {
    return Math.round((actualPPH / targetPPH * 100) * 100) / 100
  }
  return 0
})

// 🔧 监听关键字段变化，自动重新获取目标值和预估值
watch(
  () => [
    editing.data.material_code,
    editing.data.line_name,
    editing.data.record_date,
    editing.data.is_whole_machine
  ],
  async () => {
    if (editing.visible) {
      await fetchTargetAndEstimateForEdit()
    }
  },
  { deep: true }
)

// 格式化达成率显示
function formatEfficiencyRate(value: any): string {
  if (value == null || value === undefined || value === '') {
    return '-'
  }

  const numValue = Number(value)
  if (isNaN(numValue)) {
    return '-'
  }

  return numValue.toFixed(2)
}

async function confirmDelete(row:Row){
  try{
    await ElMessageBox.confirm(`确认删除订单号【${row.order_number}】的整条记录吗？此操作不可恢复。`, '删除确认', { type:'warning' })
    await pphService.deleteRecord(row.id)
    ElMessage.success('删除成功')
    loadData()
  }catch(e:any){
    if(e?.message) ElMessage.error(e.message)
  }
}

// 组件挂载时初始化数据
onMounted(async () => {
  await loadLines()
  await loadAbnormalityCategories()

  // 记录维护页面采用"空白状态"策略：
  // - 不恢复搜索条件
  // - 不自动加载数据
  // - 用户必须手动输入条件并查询
  console.log('📝 记录维护页面已加载，等待用户输入查询条件')
})
</script>

<style scoped>
.filters {
  margin-bottom: 12px;
  max-width: 100%;
  overflow: hidden;
}

.search-container {
  max-width: 100%;
  overflow: hidden;
  padding-right: 16px;
}

.search-form {
  width: 100%;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-bottom: 12px;
}

.form-row .el-form-item {
  margin-right: 16px;
  margin-bottom: 0;
}

.form-row-with-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.form-fields {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  flex: 1;
}

.form-fields .el-form-item {
  margin-right: 16px;
  margin-bottom: 0;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
  margin-left: 16px;
}

.action-btn {
  width: 80px;
  flex-shrink: 0;
}

.pager {
  display: flex;
  justify-content: flex-end;
  margin-top: 8px;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .form-row .el-form-item {
    margin-right: 12px;
  }

  .search-container {
    padding-right: 12px;
  }
}

@media (max-width: 768px) {
  .form-row {
    flex-direction: column;
    align-items: stretch;
  }

  .form-row .el-form-item {
    margin-right: 0;
    margin-bottom: 8px;
  }

  .action-buttons {
    justify-content: center;
  }
}
</style>
